package com.bmw.seed.service.impl;

import com.bmw.seed.dao.RUserDao;
import com.bmw.seed.dao.RankDao;
import com.bmw.seed.model.RUser;
import com.bmw.seed.model.Rank;
import com.bmw.seed.service.RankService;
import com.bmw.seed.util.bean.RankResp;
import com.bmw.seed.util.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Classname: RankServiceImpl
 * Package: com.bmw.seed.service.impl
 * Description:
 *
 * @Author 王少伟
 * @Create 2024/1/31 10:52
 * @Version 1.8
 */
@Slf4j
@Service("rankService")
public class RankServiceImpl implements RankService {
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    RUserDao rUserDao;
    @Autowired
    RankDao rankDao;
    @Override
    public List<RankResp> list3() {
        String key  = "rank:list";
        Set<ZSetOperations.TypedTuple<Object>> set = redisUtil.zrevrangeByScoreWithScores(key,0D,10D);
        Iterator<ZSetOperations.TypedTuple<Object>> it = set.iterator();
        int rank  = 1;
        List<RankResp> list = new ArrayList<>();
        while(it.hasNext()){
            ZSetOperations.TypedTuple<Object> e = it.next();
            RankResp resp = new RankResp();
            RUser user = rUserDao.selectByPrimaryKey(Long.valueOf(e.getValue().toString()));
            resp.setPhone(user.getPhone());
            resp.setAmount(new BigDecimal(e.getScore()));
            resp.setRank(rank);
            list.add(resp);
            rank++;
        }
        return list;
    }

    @Override
    public List<Rank> list3(String word) {
        record(word);
        return rankDao.match(word);
    }

    public Double record(String word) {
        try {
            return redisUtil.zincrby("NEWS_SEARCH:", word, 1);
        } catch (Exception e) {
            log.error("===[排行时出现异常：excp={}]===", e);
        }
        return 0D;
    }
}
